import axios from 'axios'
import { login } from '@/api/tiantai'
const instance = axios.create({
  baseURL: '/api/v2.0',
  timeout: 10000
})
// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json'
    config.headers['token'] = localStorage.getItem('token') || ''
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

let isRefreshing = false

// 添加响应拦截器
instance.interceptors.response.use(
  async res => {
    let notLogin = false
    if (
      res.headers['content-type'] == 'text/html;charset=utf-8' &&
      toString(res.data).includes('"code":4000')
    ) {
      notLogin = true
    }
    if (res.data.code == 4000 || res.data.code == 2000 || notLogin) {
      if (!isRefreshing) {
        localStorage.removeItem('token')
        isRefreshing = true
        return login({
          loginName: 'cq241212qxzc',
          loginPwd: 'cq241212qxzc'
        })
          .then(login => {
            localStorage.setItem('token', login.data.token)
            res.config.headers['token'] = res.data.token
            isRefreshing = false
            return instance(res.config)
          })
          .catch(err => {
            console.log(err)
            return Promise.reject(err)
          })
          .finally(() => {
            isRefreshing = false
          })
      }
    }
    return res.data
  },
  err => {
    console.log(err)
    return Promise.reject(err)
  }
)

export default instance
